package com.symria.client.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONObject;
import com.symria.framework.page.ATTPage;
import com.symria.framework.page.Page;
import com.symria.framework.page.PagerFactory;
import com.symria.framework.util.BaseAction;
import com.symria.framework.util.DateUtil;
import com.symria.framework.util.NumberUtil;
import com.symria.framework.util.StringUtil;
import com.symria.server.bo.app.APPService;
import com.symria.server.bo.campaign.CampaignService;
import com.symria.server.bo.role.RoleService;
import com.symria.server.po.AdAppReport;
import com.symria.server.po.AdCampaign;
import com.symria.server.po.AdContent;
import com.symria.server.po.AdPush;
import com.symria.server.po.AppDateReport;
import com.symria.server.po.AppInfo;
import com.symria.server.po.Constant;
import com.symria.server.po.PackDateReport;
import com.symria.server.po.PackInfo;
import com.symria.server.po.SysAreaInfo;
import com.symria.system.constants.ATTSystem;
import com.symria.system.constants.BaseAttribute;
import com.symria.system.util.ExcelUtil;
import com.symria.system.util.ReportBean;

public class CampaignAction extends BaseAction {

	private CampaignService campaignService;
	private APPService appService;
	private RoleService roleService;
	private AdCampaign campaign;
	private AdContent content;
	private AdAppReport aar;
	private AppDateReport adr;
	private AppInfo ap;
	private Date beginDate;
	private Date endDate;
	private String opers[];
	private Integer[] areas;
	private Integer id;
	private String state;
	private File imgFile;
	private String imgFileFileName;
	private File imgOne;
    private File imgTwo;
    private String imgOneFileName;
    private String imgTwoFileName;
	private String viewType;
	private Integer level;
	private String orderBy;
	private String imei;
	private Date createDate;
	private Date lastDate;
	private PackInfo pack;
	private File file;
	private Integer actionCount;
	private Integer factCount;
	private PackDateReport pdr;
	private InputStream fileInputStream;
	private String downloadFileName;
	private Integer packId;
	private String packIds;
	private Integer channelId;
	private String packName;
	private String total;
	private Double price;
	
	public File getImgOne() {
		return imgOne;
	}
	public void setImgOne(File imgOne) {
		this.imgOne = imgOne;
	}
	public File getImgTwo() {
		return imgTwo;
	}
	public void setImgTwo(File imgTwo) {
		this.imgTwo = imgTwo;
	}
	public String getImgOneFileName() {
		return imgOneFileName;
	}
	public void setImgOneFileName(String imgOneFileName) {
		this.imgOneFileName = imgOneFileName;
	}
	public String getImgTwoFileName() {
		return imgTwoFileName;
	}
	public void setImgTwoFileName(String imgTwoFileName) {
		this.imgTwoFileName = imgTwoFileName;
	}
	public AppDateReport getAdr() {
		return adr;
	}
	public void setAdr(AppDateReport adr) {
		this.adr = adr;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public String getTotal() {
		return total;
	}
	public void setTotal(String total) {
		this.total = total;
	}
	public String getPackIds() {
		return packIds;
	}
	public void setPackIds(String packIds) {
		this.packIds = packIds;
	}
	public Integer getPackId() {
		return packId;
	}
	public void setPackId(Integer packId) {
		this.packId = packId;
	}
	public Integer getChannelId() {
		return channelId;
	}
	public void setChannelId(Integer channelId) {
		this.channelId = channelId;
	}
	public String getPackName() {
		return packName;
	}
	public void setPackName(String packName) {
		this.packName = packName;
	}
	public InputStream getFileInputStream() {
		return fileInputStream;
	}
	public void setFileInputStream(InputStream fileInputStream) {
		this.fileInputStream = fileInputStream;
	}
	public String getDownloadFileName() {
		return downloadFileName;
	}
	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}
	public Integer getActionCount() {
		return actionCount;
	}
	public void setActionCount(Integer actionCount) {
		this.actionCount = actionCount;
	}
	public Integer getFactCount() {
		return factCount;
	}
	public void setFactCount(Integer factCount) {
		this.factCount = factCount;
	}
	public PackDateReport getPdr() {
		return pdr;
	}
	public void setPdr(PackDateReport pdr) {
		this.pdr = pdr;
	}
	public Date getLastDate() {
		return lastDate;
	}
	public void setLastDate(Date lastDate) {
		this.lastDate = lastDate;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public PackInfo getPack() {
		return pack;
	}
	public void setPack(PackInfo pack) {
		this.pack = pack;
	}
	public String getOrderBy() {
		return orderBy;
	}
	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}
	public String getImei() {
		return imei;
	}
	public void setImei(String imei) {
		this.imei = imei;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	public Integer getLevel() {
		return level;
	}
	public void setLevel(Integer level) {
		this.level = level;
	}
	public AdAppReport getAar() {
		return aar;
	}
	public void setAar(AdAppReport aar) {
		this.aar = aar;
	}
	public Date getBeginDate() {
		return beginDate;
	}
	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	public String getViewType() {
		return viewType;
	}
	public void setViewType(String viewType) {
		this.viewType = viewType;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public File getImgFile() {
		return imgFile;
	}
	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}
	public String getImgFileFileName() {
		return imgFileFileName;
	}
	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}
	public AdContent getContent() {
		return content;
	}
	public void setContent(AdContent content) {
		this.content = content;
	}
	public String[] getOpers() {
		return opers;
	}
	public void setOpers(String[] opers) {
		this.opers = opers;
	}
	public Integer[] getAreas() {
		return areas;
	}
	public void setAreas(Integer[] areas) {
		this.areas = areas;
	}
	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public CampaignService getCampaignService() {
		return campaignService;
	}
	public void setCampaignService(CampaignService campaignService) {
		this.campaignService = campaignService;
	}
	public AdCampaign getCampaign() {
		return campaign;
	}
	public void setCampaign(AdCampaign campaign) {
		this.campaign = campaign;
	}
	public AppInfo getAp() {
		return ap;
	}
	public void setAp(AppInfo ap) {
		this.ap = ap;
	}
	
	public APPService getAppService() {
		return appService;
	}
	public void setAppService(APPService appService) {
		this.appService = appService;
	}
	/**
	 *功能描述:添加广告
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String toCampaign(){
		AdCampaign ad=campaignService.getObject(id, AdCampaign.class);
		setAttr("customList",campaignService.queryCustomInfo());
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		return SUCCESS;
	}
	/**
	 *功能描述:
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String suCampaign(){
		AdCampaign ad=campaignService.getObject(id, AdCampaign.class);
		if(ad!=null && campaign!=null){
			campaignService.updateAdCampaignOne(campaign, ad);
		}else if(campaign!=null){
			campaignService.saveAdCampaignOne(campaign);
			this.setId(campaign.getAdId());
		}
		return SUCCESS;
	}
	
	public String campaignCheck(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		AdPush push = campaignService.getObject(id, AdPush.class);
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		setAttr(BaseAttribute.AD_PUSH, push);
		return SUCCESS;
	}
	
	public String campaignDetail(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		AdContent content = campaignService.getObject(id, AdContent.class);
		if(ad!=null){
			//地区
			List<SysAreaInfo> list = campaignService.queryAreaInfo();
			//运营商
			List<Constant> operList = roleService.queryConstantsByPcode(ATTSystem.CONSTANTS_OPER, ATTSystem.LOGIC_TRUE);
			
			setAttr("operList", operList);
			setAttr("areaList", list);
		}
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		setAttr(BaseAttribute.AD_CONTENT, content);
		return SUCCESS;
	}
	
	/**
	 *功能描述:
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String toCampaignTwo(){
		AdCampaign ad=campaignService.getObject(id, AdCampaign.class);
		//地区
		List<SysAreaInfo> list = campaignService.queryAreaInfo();
		//运营商
		List<Constant> operList = roleService.queryConstantsByPcode(ATTSystem.CONSTANTS_OPER, ATTSystem.LOGIC_TRUE);
		//网络类型
		List<Constant> netList = roleService.queryConstantsByPcode(ATTSystem.CONSTANTS_NET, ATTSystem.LOGIC_TRUE);
		//平台
		List<Constant> osList = roleService.queryConstantsByPcode(ATTSystem.CONSTANTS_OS, ATTSystem.LOGIC_TRUE);
		
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		setAttr("operList", operList);
		setAttr("netList", netList);
		setAttr("osList", osList);
		setAttr("areaList", list);
		return SUCCESS;
	}
	public String campaignTwoCheck(){
		List<Integer> list = campaignService.queryAreaIdByadId(id);
		List<String> list1 = campaignService.queryAdOperateByadId(id);
		JSONObject obj = new JSONObject();
		obj.element("areaReg", createAreaReg(list));
		obj.element("operReg", createOperReg(list1));
		setAjaxData(obj.toString());
		return SUCCESS;
	}
	
	public static String createAreaReg(List<Integer> list){
		StringBuffer menuReg= new StringBuffer("");
		boolean b = true;
		for(Integer id:list){
			if(b){
				menuReg.append(id);
				b=false;
			}else{
				menuReg.append("|"+id);
			}
		}
		return menuReg.toString();
	}
	public static String createOperReg(List<String> list){
		StringBuffer menuReg= new StringBuffer("");
		boolean b = true;
		for(String oper:list){
			if(b){
				menuReg.append(oper);
				b=false;
			}else{
				menuReg.append("|"+oper);
			}
		}
		return menuReg.toString();
	}
	/**
	 *功能描述:
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String suCampaignTwo(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		if(null!=ad && null!=campaign){
		   campaignService.updateAdCampaignTwo(campaign, ad);
	       if(null!=opers){
	    	   campaignService.updateAdOperate(ad, opers);
	       }
	       if(null!=areas){
	    	   campaignService.updateAdArea(ad, areas);
	       }
		}
		return SUCCESS;
	}
	/**
	 *功能描述:
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String toCampaignThree(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		AdContent content = campaignService.getObject(id, AdContent.class);
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		setAttr(BaseAttribute.AD_CONTENT, content);
		return SUCCESS;
	}
	/**
	 *功能描述:
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String suCampaignThree(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		AdContent c = campaignService.getObject(id, AdContent.class);
		if(ad!=null){
			if(null!=c && content!=null){
				campaignService.updateAdContent(c, imgFile, imgFileFileName, imgOne, imgOneFileName, imgTwo, imgTwoFileName, content);//(c, imgFile, imgFileFileName, content);
			}else if(content!=null){
				content.setAdId(ad.getAdId());
				campaignService.saveAdContent(c, imgFile, imgFileFileName, imgOne, imgOneFileName, imgTwo, imgTwoFileName);//(content, imgFile, imgFileFileName);
			}
			campaignService.updateForAdCampaignDone(ad);
		}
		setAttr(BaseAttribute.AD_CAMPAIGN, ad);
		return SUCCESS;
	}
	public String updateCampaignState(){
		AdCampaign ad = campaignService.getObject(id, AdCampaign.class);
		if(ad!=null){			
			campaignService.updateCampaignState(ad, state,price);
			campaignService.callPush(ad);
		}
		return SUCCESS;
	}
	
	public String campaignReport(){
		Page page = PagerFactory.createPage();
		campaignService.campaignReport(aar, beginDate, endDate, page);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	
	/**
	 *功能描述:查询广告
	 * 2013-5-6
	 * @return
	 * admin
	 */
	public String searchCampaign(){
		Page page = PagerFactory.createPage();
		campaignService.searchAdCampaign(campaign,viewType, page);
        setAttr(ATTPage.PAGE_LIST,page);		
		return SUCCESS;
	}
	
	/**
	 *功能描述:
	 * 2013-9-5
	 * @return
	 * admin
	 */
	public String searchPackReport(){
		Page page = PagerFactory.createPage();
		campaignService.searchPackReport(pdr,beginDate,endDate,ATTSystem.LOGIC_TRUE, page);
		setAttr(ATTPage.PAGE_LIST,page);
		return SUCCESS;
	}
	
	public String updatePackReport(){
		
		PackDateReport pdr = null;
		if(!StringUtil.isEmpty(id)){
			pdr = campaignService.getObject(id, PackDateReport.class);
		}
		if(!StringUtil.isEmpty(actionCount) && !StringUtil.isEmpty(factCount)){
			campaignService.updatePackDateReport(pdr, actionCount, factCount);
		}
		JSONObject o  =new JSONObject();
		o.accumulate("id", id);
		setAjaxData(o.toString());
		return SUCCESS;
	}
	
	public String comfirmPackReport(){
		Page page = PagerFactory.createPage();
		campaignService.searchPackReport(pdr,beginDate,endDate,ATTSystem.LOGIC_FALSE, page);
		setAttr(ATTPage.PAGE_LIST,page);
		return SUCCESS;
	}
	
	
	public String searchImei(){
		Page page = PagerFactory.createPage();
		page.setPageSize(50);
		campaignService.searchImei(orderBy, imei, createDate, lastDate, page);
		setAttr(ATTPage.PAGE_LIST,page);
		return SUCCESS;
	}
	
	
	/**
	 *功能描述:查询广告投送
	 * 2013-8-6
	 * @return
	 * admin
	 */
	public String searchPush(){
		Page page = PagerFactory.createPage();
		campaignService.searchPush(page);
		setAttr(ATTPage.PAGE_LIST, page);
		setAttr("level",campaignService.searchPushLevel());
		return SUCCESS;
	}
	public String searchApp(){
		Page page = PagerFactory.createPage();
		campaignService.searchApp(ap, beginDate, endDate, page);
		setAttr("app", ap);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	public String updatePushLeval(){
		AdPush p = campaignService.getObject(id, AdPush.class);
		if(null!=p&&null!=level){
			p.setLevel(level);
			campaignService.updateObject(p);
		}
		return SUCCESS;
	}
	
	public String toPackInfo(){
		PackInfo pack = campaignService.getObject(id, PackInfo.class);
		setAttr(ATTSystem.PACK_INFO, pack);
		setAttr(BaseAttribute.LIST, campaignService.queryChannel());
		setAttr("customList",campaignService.queryCustomInfo());
		return SUCCESS;
	}
	public String suPackInfo(){
		if(pack==null){return SUCCESS;}
		PackInfo p = campaignService.getObject(id, PackInfo.class);
		if(null==p ){
			campaignService.savePackInfo(pack);
		}else {
			campaignService.updatePackInfo(pack, p);
		}
		return SUCCESS;
	}
	public String copyPackInfo(){
		PackInfo p = campaignService.getObject(id, PackInfo.class);
		if(null!=p){
			PackInfo cp = new PackInfo();
			cp.setApkName(p.getApkName());
			cp.setCheckUrl(p.getCheckUrl());
			cp.setBeginDate(p.getBeginDate());
			cp.setGetMoney(p.getGetMoney());
			cp.setPackPrice(p.getPackPrice());
			cp.setPushDesc(p.getPushDesc());
			cp.setPackOwner(p.getPackOwner());
			cp.setMobile(p.getMobile());
			cp.setPackName(p.getPackName()+"_复制");
			cp.setPackDesc(p.getPackDesc());
			cp.setState(ATTSystem.LOGIC_FALSE);
			campaignService.saveObject(cp);
		}
		return SUCCESS;
	}
	
	public String importPackReport(){
		if(file!=null){
			List<PackDateReport> l = this.readAppReport(file);
			for(PackDateReport pdr:l){
				campaignService.saveOrUpdatePackDateReport(pdr);
			}
		}
	   return SUCCESS;
	}
	public List<PackDateReport> readAppReport(File csvFile){
		List<PackDateReport> list = new ArrayList<PackDateReport>();
		try {
			//0:包编号 1:渠道编号 2:日期 3:效果数 4:包价格 5:结算数
			FileReader reader = new FileReader(csvFile);
			LineNumberReader line = new LineNumberReader(reader);
			String lineStr = null;
			while((lineStr=line.readLine())!=null){
				if(line.getLineNumber()>1){
					String[] strs=lineStr.split(",");
					//System.out.println(strs.length+"--------------------------");
					if(strs.length>=6){
						PackDateReport pdr = new PackDateReport();
						pdr.setPackId(NumberUtil.getInteger(strs[0], 0));
						pdr.setChannelId(NumberUtil.getInteger(strs[1], 0));
						pdr.setCreateDate(DateUtil.getDate(strs[2]));
						pdr.setActionCount(NumberUtil.getInteger(strs[3], 0));
						pdr.setFactCount(NumberUtil.getInteger(strs[5], 0));
						/**
						Double rate = NumberUtil.getDouble(strs[5], 1);//比率
						rate = rate>1?1:rate;
						Double ac=Math.ceil(NumberUtil.getDouble(strs[3], 0d)*rate); //(NumberUtil.getInteger(strs[3], 0));
						pdr.setFactCount(ac.intValue());
						*/
						pdr.setPackPrice(NumberUtil.getDouble(strs[4], 0d));
						pdr.setFactMoney(pdr.getPackPrice()*pdr.getFactCount());
						pdr.setState(ATTSystem.LOGIC_TRUE);
						if(!StringUtil.isEmpty(pdr.getCreateDate())){
							list.add(pdr);
						}
					}
				}
			}
		} catch (Exception e) {
			//return list;
			e.printStackTrace();
		}
		return list;
	}
	
	public String searchPackInfo(){
		Page page = PagerFactory.createPage();
		campaignService.searchPackInfo(pack, page);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	public String searchPackDateReportByDate(){
		filterDate();
		ReportBean rb = new ReportBean();
		List<PackInfo> list = campaignService.searchPackDateReportByDate(beginDate, endDate,getPackIdsList(),channelId, rb);
		setAttr(BaseAttribute.LIST, list);
		setAttr("rb",rb);
		return SUCCESS;
	}
	private List<Integer> getPackIdsList(){
		if(!StringUtil.isEmpty(packIds)){
			String[] ids=packIds.split(",");
			List<Integer> l = new ArrayList<Integer>();
			for(String id:ids){
				l.add(NumberUtil.parseInteger(id, 0));
			}
			return l;
		}
		return null;
	}
	
	public String searchDailyReport(){
		Page page = PagerFactory.createPage();
		campaignService.searchDailyReport(page, beginDate, endDate);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	public String searchReport(){
		Page page = PagerFactory.createPage();
		campaignService.searchReport(aar, beginDate, endDate, page);
		setAttr(ATTPage.PAGE_LIST, page);
		setAttr("sum", campaignService.finedSumCount(aar, beginDate, endDate));
		return SUCCESS;
	}
	public String appReport(){
		Page page = PagerFactory.createPage();
		campaignService.appReport(adr, beginDate, endDate, page);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	
	public String dailyReport(){
		
		Page page = PagerFactory.createPage();
		campaignService.dailyReport(beginDate, endDate, page);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	
	public String excelDown(){
		filterDate();
		ReportBean rb = new ReportBean();
		List<PackInfo> list = campaignService.searchPackDateReportByDate(beginDate, endDate,getPackIdsList(),channelId, rb);
		String fileName=DateUtil.getFormatDate(beginDate, "MMdd")+"_"+DateUtil.getFormatDate(endDate, "MMdd");
		String path=ExcelUtil.createFinanceExcel(fileName, list, rb);
		try {
			fileInputStream = new FileInputStream(new File(path));
			downloadFileName=fileName+".xls";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	private void filterDate(){
		if(null==beginDate){
			beginDate=DateUtil.get00HourDate(DateUtil.getFistDayOfMonth());
		}
		if(null==endDate){
			endDate=DateUtil.get00HourDate(new Date());
		}
	}
	
	public String searchPackReportByCustom(){
		filterDate();
		Page page = PagerFactory.createPage();
		campaignService.searchPackReportByCustom(beginDate, endDate, packId, channelId,page,total);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	public String searchPackReportByChannel(){
		filterDate();
		Page page = PagerFactory.createPage();
		campaignService.searchPackReportByChannel(beginDate, endDate, packId, channelId,page,total);
		setAttr(ATTPage.PAGE_LIST, page);
		return SUCCESS;
	}
	
	public String manageApp(){
		
		AppInfo app=appService.findAppInfoById(ap.getAppId());
		setAttr("app", app);
		return SUCCESS;
	}
	
	public String suApp(){
		appService.updateAppWithAbsence(ap);
		return SUCCESS;
	}
	
}
